package com.liyujie.networkrequest.remotedata.systemapi;


import androidx.lifecycle.ViewModelProvider;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.liyujie.networkrequest.remotedata.BaseApiModule;
import com.liyujie.networkrequest.remotedata.BaseInterceptor;
import com.liyujie.networkrequest.remotedata.ViewModelFactory;
import com.liyujie.networkrequest.utils.HttpsUtils;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


@Module
public class SystemApiServiceModule extends BaseApiModule {

    @Provides
    @Singleton
    public Retrofit provideRetrofit() {
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.hostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        okHttpClientBuilder.addInterceptor(new BaseInterceptor());
        okHttpClientBuilder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
        okHttpClientBuilder.connectTimeout(60, TimeUnit.SECONDS); // 设置连接超时时间为30秒
        okHttpClientBuilder.readTimeout(60, TimeUnit.SECONDS); // 设置读取超时时间为30秒
        okHttpClientBuilder.writeTimeout(60, TimeUnit.SECONDS);// 设置写入超时时间为30秒
        OkHttpClient client = okHttpClientBuilder.build();
        Gson mGson = new GsonBuilder().setLenient().create();
        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(mGson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(SYSTEM_URL)
                .build();
        return retrofit;
    }

    @Provides
    @Singleton
    SystemApiService getApiCallInterface(Retrofit retrofit) {
        return retrofit.create(SystemApiService.class);
    }


    @Provides
    @Singleton
    ViewModelProvider.Factory getViewModelFactory(SystemApiService myRepository) {
        return new ViewModelFactory(myRepository);
    }
}
